package ferp.android.dialogs;

import android.content.Context;
import android.content.DialogInterface;
import android.util.DisplayMetrics;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.TableLayout;
import android.widget.TextView;
import ferp.android.GUI;
import ferp.android.R;
import ferp.android.managers.ProfileManager;
import ferp.android.views.PoolView;
import ferp.android.widgets.BidView;
import ferp.android.widgets.buttons.TextButton;
import ferp.core.game.Bid;
import ferp.core.game.Game;
import ferp.core.game.Input;
import ferp.core.player.Profile;

/**
* User: igorgok
* Date: 5/29/12 2:21 PM
*/
public class PoolDialog extends Dialog
{
  public interface Listener
  {
    void onPoolDialogDismiss(Input.PoolUserChoice puc);
    void onSendReportRequested();
    void onShareClick();
  }

  public static PoolDialog create(Context context, final Listener listener)
  {
    Profile profile = ProfileManager.instance(context).getCurrentProfile();

    return profile == null || profile.game() == null ? null : new PoolDialog(context, listener);
  }

  public void set(boolean menu)
  {
    Profile profile = ProfileManager.instance(getContext()).getCurrentProfile();
    Game g = profile.game();

    pool.showWatermark(g.replay);

    // show/hide buttons bar
    layoutButtons.setVisibility(menu ? View.GONE : View.VISIBLE);

    // show/hide "replay" button - can't use 'isShown' method as a dialog itself is not shown yet
    if (layoutButtons.getVisibility() == View.VISIBLE)
      replay.setVisibility(profile.games().initial == null ? View.GONE : View.VISIBLE);

    // show tricks only at the end
    if (menu)
      layoutTricks.setVisibility(View.GONE);
    else
    {
      bv.show(g.declarer() == null ? Bid.pass() : g.getDeclarerBid().current, true);

      for (int id = 0; id < Game.PLAYERS; ++id)
      {
        String text = String.valueOf(g.getTricks(id));
        //int color = Color.BLACK;

        switch (g.getBid(id).current.type)
        {
          case WITHOUT_3:
            // a terrible hack!
            Bid b = new Bid(g.getBid(id).current);

            b.type = Bid.Type.PLAY;
            text = String.valueOf(b.tricks - 3);
            bv.show(b, false);
/*
          case PLAY:
            color = g.getTricks(id) < g.getBid(id).current.tricks ? Color.RED : Color.GREEN;
            break;
          case MISERE:
            color = g.getTricks(id) == 0 ? Color.GREEN : Color.RED;
            break;
          case WHIST:
            color = GUI.Color.NORMAL;
            break;
          case PASS:
            color = Color.DKGRAY;
*/
            break;
        }

        //tricks[id].setBackgroundResource(bgr);
        tricks[id].setText(text);
        tricks[id].setTextColor(GUI.Color.NORMAL);
      }

      layoutTricks.setVisibility(View.VISIBLE);
    }
  }

  @Override
  public boolean onCreateOptionsMenu(Menu menu)
  {
    getOwnerActivity().getMenuInflater().inflate(R.menu.pool, menu);
    menu.findItem(R.id.pool_report_game).setIcon(android.R.drawable.ic_menu_send);

    return true;
  }

  @Override
  public boolean onMenuItemSelected(int featureId, MenuItem item)
  {
    switch (item.getItemId())
    {
      case R.id.pool_report_game:
        listener.onSendReportRequested();
        return true;

      default:
        return super.onMenuItemSelected(featureId, item);
    }
  }

  /**
   *
   * @param context
   * @param listener
   * Make specific button non-clickable once it clicked.
   * No need to reset button's clickable state as the dialog is removed in onPoolDialogDismiss event.
   */
  private PoolDialog(final Context context, final Listener listener)
  {
    super(context, R.layout.dialog_pool);

    this.listener = listener;

    setCancelable(true);
    setOnCancelListener(new OnCancelListener()
    {
      @Override
      public void onCancel(DialogInterface dialogInterface)
      {
        // use pool view's 'icClickable' method as indicator to prevent processing multiply events
        if (pool.isClickable())
        {
          pool.setClickable(false);
          puc = Input.PoolUserChoice.CONTINUE;
        }
      }
    });

    pool = (PoolView)findViewById(R.id.dlg_pool_view);

    registerForContextMenu(pool);
    pool.setOnCreateContextMenuListener(this);

    pool.setOnClickListener(new View.OnClickListener()
    {
      public void onClick(View view)
      {
        if (view.isClickable())
        {
          view.setClickable(false);
          puc = Input.PoolUserChoice.CONTINUE;

          dismiss();
        }
      }
    });

    setOnDismissListener(new OnDismissListener()
    {
      public void onDismiss(DialogInterface dialogInterface)
      {
        listener.onPoolDialogDismiss(puc);
      }
    });

    layoutTricks = (TableLayout)findViewById(R.id.dlg_pool_layout_tricks);
    layoutButtons = (LinearLayout)findViewById(R.id.dlg_pool_layout_buttons);

    tricks[0] = resolveTextView(R.id.dlg_pool_tricks_human);
    tricks[1] = resolveTextView(R.id.dlg_pool_tricks_left);
    tricks[2] = resolveTextView(R.id.dlg_pool_tricks_right);
    bv = (BidView)findViewById(R.id.dlg_pool_bid);

    findViewById(R.id.dlg_pool_btn_replay_initial_poistion).setOnClickListener(new View.OnClickListener()
    {
      @Override
      public void onClick(View view)
      {
        if (view.isClickable())
        {
          view.setClickable(false);
          puc = Input.PoolUserChoice.SHOW_INITIAL_POSITION;

          dismiss();
        }
      }
    });

    replay = (TextButton)findViewById(R.id.dlg_pool_btn_replay);
    replay.setOnClickListener(new View.OnClickListener()
    {
      @Override
      public void onClick(View view)
      {
        if (view.isClickable())
        {
          view.setClickable(false);
          puc = Input.PoolUserChoice.REPLAY;

          dismiss();
        }
      }
    });

    View share = findViewById(R.id.dlg_pool_btn_share);
    share.setOnClickListener(new View.OnClickListener()
    {
      @Override
      public void onClick(View view)
      {
        listener.onShareClick();
      }
    });

    boolean landscape = ProfileManager.instance(context).getCurrentProfile().isLandscape();
    DisplayMetrics metrics = new DisplayMetrics();
    LinearLayout.LayoutParams lp1 = new LinearLayout.LayoutParams(layoutButtons.getLayoutParams());
    LinearLayout.LayoutParams lp2 = new LinearLayout.LayoutParams(bv.getLayoutParams());

    ((WindowManager)context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getMetrics(metrics);
    // button layout height
    lp1.height = Math.round(Math.min(metrics.widthPixels, metrics.heightPixels) * (landscape ? 0.1f : 0.13f));
    layoutButtons.setLayoutParams(lp1);
    // bid view height
    lp2.height = Math.round(lp1.height / 2.0f);
    bv.setLayoutParams(lp2);

    //Log.debug(Log.TAG, "PD: display is " + metrics.widthPixels + "x" + metrics.heightPixels + ", buttons height " + lp.height);

    //layout.measure(View.MeasureSpec.makeMeasureSpec(metrics.widthPixels, View.MeasureSpec.EXACTLY), View.MeasureSpec.makeMeasureSpec(metrics.heightPixels, View.MeasureSpec.EXACTLY));

    //Log.debug(Log.TAG, "PD: " + pool.getMeasuredWidth() + "x" + pool.getMeasuredHeight());
  }

  private TextView resolveTextView(int id)
  {
    TextView tv = (TextView)findViewById(id);

    tv.setTypeface(GUI.Font.BOLD);

    return tv;
  }

  // pool view
  private PoolView pool;
  // dialog event listener
  private final Listener listener;

  // tricks table layout
  private final TableLayout layoutTricks;
  // buttons layout
  private LinearLayout layoutButtons;

  // array of trick text views
  private final TextView[] tricks = new TextView[Game.PLAYERS];
  // bid view
  private BidView bv;
  // buttons
  private TextButton replay;
  // user choice
  private Input.PoolUserChoice puc = Input.PoolUserChoice.CONTINUE;
}
